/**
 * 
 */
package com.fashion.server.aop;

import com.alibaba.fastjson.JSON;
import com.fashion.server.common.IConstants;
import com.fashion.server.domain.response.ResponseData;
import com.fashion.server.utils.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;

import java.util.ArrayList;
import java.util.List;


/**
 * controller参数校验
 * 
 * @author WangXin
 */
public class ParamsValidateAspect {

	private static final Logger logger = Logger.getLogger(ParamsValidateAspect.class);

	private static final List<String> notParamOrNotJsonMethod = new ArrayList<String>();
	static {
		notParamOrNotJsonMethod.add("monitor");
		notParamOrNotJsonMethod.add("skuGroup");
	}

	public Object validateAround(ProceedingJoinPoint jp) throws Throwable {
		ResponseData responseData = this.validate(jp);
		if (responseData.getCode() == IConstants.ResponseDefine.Code.SUCCESS_200.getIndex()) {
			return jp.proceed();
		} else {
			return JsonUtil.toJSONString(responseData, false);
		}
	}

	private ResponseData validate(ProceedingJoinPoint jp) {
		Object[] args = jp.getArgs();
		try {
			// 不校验的方法
			if (notParamOrNotJsonMethod.contains(jp.getSignature().getName())) {
				return new ResponseData(IConstants.ResponseDefine.Code.SUCCESS_200.getIndex());
			}
			// 参数校验
			if (args == null || args.length == 0) {
				return new ResponseData(IConstants.ResponseDefine.Code.ERROR_402.getIndex(), "参数错误:缺少data参数");
			}
			Object arg0 = args[0];
			if (arg0 == null) {
				return new ResponseData(IConstants.ResponseDefine.Code.ERROR_402.getIndex(), "参数错误:缺少data参数");
			}
			if (StringUtils.isBlank(arg0.toString())) {
				return new ResponseData(IConstants.ResponseDefine.Code.ERROR_402.getIndex(), "参数错误:data参数不能为空");
			}
			// 是否是json格式
			try {
				JSON.parseObject(arg0.toString());
			}
			catch (Exception e1) {
				logger.warn(jp.getSignature().toString() + ":" + e1.toString());
				return new ResponseData(IConstants.ResponseDefine.Code.ERROR_402.getIndex(), "参数错误:data必须是json格式。" + e1.toString());
			}
		}
		catch (Exception e) {
			logger.warn(e.toString());
		}
		return new ResponseData(IConstants.ResponseDefine.Code.SUCCESS_200.getIndex());
	}

}
